﻿using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Coldairarrow.Util.Helper;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Coldairarrow.Business.FileBusiness
{
    public class Flie_BaseBusiness
    {
        //接口名称
        public string InterfaceName { get; set; }
        //接口配置
        public List<Base_InterfaceOption> interfaceOption { get; set; }
        //表格映射
        public Dictionary<string, string> tableField { get; set; } = new Dictionary<string, string>();
        //索引字段
        public List<string> indexFields { get; set; } = new List<string>();


        //查询总条数
        public int BackupFileNum { get; set; }
        public SqlServerHelper SqlDb;
        public OracleHelper OracleDb;
        public string ConString;
        public Flie_BaseBusiness()
        {

        }


        // 执行请求前事件
        public delegate void BeforeBackupFileEventHandler(object sender, BackupFileEventArgs BackupFileEventArgs);
        public event BeforeBackupFileEventHandler BeforeBackupFileEvent;
        protected virtual void BeforeBackupFile(BackupFileEventArgs BackupFileEventArgs)
        {
            BeforeBackupFileEventHandler handler = BeforeBackupFileEvent;
            handler?.Invoke(this, BackupFileEventArgs);
        }

        // 执行请求中事件
        public delegate void OnBackupFileEventHandler(object sender, BackupFileEventArgs BackupFileEventArgs);
        public event OnBackupFileEventHandler OnBackupFileEvent;
        protected virtual void OnBackupFile(BackupFileEventArgs BackupFileEventArgs)
        {
            OnBackupFileEventHandler handler = OnBackupFileEvent;
            handler?.Invoke(this, BackupFileEventArgs);
        }

        // 执行请求后事件
        public delegate void AfterBackupFileEventHandler(object sender, BackupFileEventArgs BackupFileEventArgs);
        public event AfterBackupFileEventHandler AfterBackupFileEvent;
        protected virtual void AfterBackupFile(BackupFileEventArgs BackupFileEventArgs)
        {
            AfterBackupFileEventHandler handler = AfterBackupFileEvent;
            handler?.Invoke(this, BackupFileEventArgs);
        }
        /// <summary>
        /// 执行非查询的API操作
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="datas"></param>
        /// <param name="APIOption"></param>
        /// <param name="db"></param>
        public async Task ExecuteBackupFile(List<AttaInfo> datas, Base_InterfaceOption APIOption, SqlServerHelper db)
        {

            if (datas.Count > 0)
            {

                HttpClient client = new HttpClient();
                BackupFileEventArgs eventArgs = new BackupFileEventArgs();
                eventArgs.APIOption = APIOption;
                eventArgs.BasePath = APIOption.TargetUrl;
                string msg = "";
                bool erroFlag = false;
                await Task.Run(() =>
                {

                    datas.ForEach(d =>
                    {

                        try
                        {
                            eventArgs.AttaInfo = d;
                            eventArgs.Path = eventArgs.BasePath + d.Path;
                            eventArgs.FullPath = eventArgs.BasePath + d.FullPath;
                            eventArgs.Url = d.Url;
                            //执行请求前事件
                            BeforeBackupFile(eventArgs);
                            //执行文件请求及备份
                            if ((!eventArgs.FullPath.IsNullOrEmpty() && !eventArgs.Url.IsNullOrEmpty()) && eventArgs.IsExist)
                            {
                                client.Url = eventArgs.Url;
                                msg = client.FileRequest(eventArgs.FullPath);
                                if (msg == "OK")
                                {
                                    //记录成功数量
                                    eventArgs.Count++;
                                }
                                else
                                {
                                    //记录异常数量
                                    eventArgs.ErroCount++;
                                    AddLog(db, InterfaceName + "----" + msg, InterfaceName, APIOption.OperateType, eventArgs.FullPath);
                                }
                                eventArgs.IsExist=false;
                            }
                            //执行请求后事件
                            AfterBackupFile(eventArgs);

                        }
                        catch (Exception ex)
                        {
                            AddLog(db, InterfaceName + "----" + ex.Message, InterfaceName, APIOption.OperateType, eventArgs.FullPath);
                        }
                    });

                    if (eventArgs.ErroCount == 0)
                    {
                        AddLog(db, $"执行完成，执行总数量{datas.Count},成功总数{eventArgs.Count},异常总数{ eventArgs.ErroCount}", InterfaceName, APIOption.OperateType, "");
                    }


                });
            }

        }

        /// <summary>
        /// 添加接口日志
        /// </summary>
        /// <param name="logContent"></param>
        /// <param name="inerfaceName"></param>
        /// <param name="db"></param>
        /// <param name="inerfaceData"></param>
        /// <param name="logType"></param>
        public void AddLog(SqlServerHelper db, string logContent, string inerfaceName, string logType = " ", string inerfaceData = " ")
        {
            try
            {
                db._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
                List<DbParameter> parameters = new List<DbParameter>();
                parameters.Add(SqlStringHelper.CreateParameter("@id", IdHelper.GetId()));
                parameters.Add(SqlStringHelper.CreateParameter("@createTime", DateTime.Now));
                parameters.Add(SqlStringHelper.CreateParameter("@creatorRealName", ""));
                parameters.Add(SqlStringHelper.CreateParameter("@creatorId", "Admin"));
                parameters.Add(SqlStringHelper.CreateParameter("@logType", logType));
                parameters.Add(SqlStringHelper.CreateParameter("@logContent", logContent));
                parameters.Add(SqlStringHelper.CreateParameter("@InterfaceName", inerfaceName));
                parameters.Add(SqlStringHelper.CreateParameter("@inerfaceData", inerfaceData));
                string sqlStr = @"INSERT INTO 
           Base_InterfaceLog(Id,CreateTime,CreatorRealName,CreatorId,LogType,LogContent,InterfaceName,InterfaceData) 
            VALUES(@id,@createTime,@creatorRealName,@creatorId,@logType,@logContent,@InterfaceName,@inerfaceData)";

                db.ExecuteSql(sqlStr, parameters);
            }
            catch (Exception ex)
            {


            }
        }


    }






}
